package com.kevin.clothes.config;

import java.lang.reflect.Method;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

	@Bean(name = "spring.jedis.pool")
	@Autowired
	public JedisPool jedisPool(@Qualifier("spring.jedis.pool.config") JedisPoolConfig config,
			@Value("${spring.jedis.pool.host}") String host, @Value("${spring.jedis.pool.port}") int port) {
		return new JedisPool(config, host, port);
	}

	@Bean(name = "spring.jedis.pool.config")
	public JedisPoolConfig jedisPoolConfig(@Value("${spring.jedis.pool.config.maxTotal}") int maxTotal,
			@Value("${spring.jedis.pool.config.maxIdle}") int maxIdle,
			@Value("${spring.jedis.pool.config.maxWaitMillis}") int maxWaitMillis) {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(maxTotal);
		config.setMaxIdle(maxIdle);
		config.setMaxWaitMillis(maxWaitMillis);
		return config;
	}
	
	@Bean
	public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
}
